package org.tao.lightningmq.nameserver.store;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author lht
 * @date 2025/1/8 - 14:27
 * @description:
 */
public class ServiceInstanceManager {

    private final Map<String, ServiceInstance> serviceInstanceMap = new ConcurrentHashMap<>();

    public void putIfExist(ServiceInstance serviceInstance) {
        String key = serviceInstance.getIp() + ":" + serviceInstance.getPort();
        ServiceInstance instance = serviceInstanceMap.get(key);
        if (instance == null || instance.getFirstRegistryTime() == null) {
            throw new RuntimeException("service instance not exist");
        }
        instance.setLastHeartBeatTime(serviceInstance.getLastHeartBeatTime());
    }

    public ServiceInstance getServiceInstance(String serviceId) {
        return serviceInstanceMap.get(serviceId);
    }

    public ServiceInstance getServiceInstance(String brokerIp, Integer brokerPort) {
        return serviceInstanceMap.get(brokerIp + ":" + brokerPort);
    }

    public ServiceInstance removeServiceInstance(String serviceId) {
        return serviceInstanceMap.remove(serviceId);
    }

    public void put(ServiceInstance serviceInstance) {
        serviceInstanceMap.put(serviceInstance.getIp() + ":" + serviceInstance.getPort(), serviceInstance);
    }

    public Map<String, ServiceInstance> getServiceInstanceMap() {
        return serviceInstanceMap;
    }
}
